# backend/essay_rater.py
from flask import Blueprint, request, jsonify
import requests
import os
from dotenv import load_dotenv
import logging
from pathlib import Path

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

rater_bp = Blueprint('rater', __name__)
load_dotenv()

DEEPSEEK_API_URL = os.getenv("DEEPSEEK_API_URL")
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")

PROMPTS_DIR = Path(__file__).resolve().parent / "prompt"  # [3,6](@ref)
prompt_cache = {}  # 提示词缓存字典


def load_prompt(prompt_type="basic"):
    """动态加载提示词文件并缓存"""
    if prompt_type in prompt_cache:
        return prompt_cache[prompt_type]

    prompt_file = PROMPTS_DIR / f"{prompt_type}_evaluation.txt"
    try:
        with open(prompt_file, 'r', encoding='utf-8') as f:
            content = f.read().strip()
            prompt_cache[prompt_type] = content
            return content
    except FileNotFoundError:
        logger.error(f"提示词文件不存在: {prompt_file}")
        return None

@rater_bp.route('/rate-essay', methods=['POST'])
def rate_essay():
    print(f"API URL: {DEEPSEEK_API_URL}")  # 检查是否正确
    print(f"API Key: {'*' * 10}{DEEPSEEK_API_KEY[-4:]}" if DEEPSEEK_API_KEY else "未设置")
    # 1. 验证请求数据
    data = request.get_json()  # 使用 get_json() 替代 json
    if not data or 'text' not in data:
        return jsonify({"error": "作文内容不能为空"}), 400

    # 2. 准备API请求
    headers = {
        "Authorization": f"Bearer {DEEPSEEK_API_KEY}",
        "Content-Type": "application/json",
        "Accept": "application/json"
    }

    prompt_type = data.get('prompt_type', 'basic')
    system_prompt = load_prompt(prompt_type)

    if not system_prompt:
        return jsonify({"error": "指定的评分标准不可用"}), 400

    payload = {
        "model": "DeepSeek-R1",
        "messages": [
            {
                "role": "system",
                "content": system_prompt
            },
            {
                "role": "user",
                "content": f"请批改以下作文：\n{data['text']}"
            }
        ],
        "temperature": 0.7,
        "stream": False
    }

    try:
        # 3. 发送请求并记录调试信息
        logger.info(f"发送请求到 DeepSeek API: {DEEPSEEK_API_URL}")
        response = requests.post(
            DEEPSEEK_API_URL,
            headers=headers,
            json=payload,
            timeout=500000
        )

        # 4. 检查响应状态
        logger.info(f"API 响应状态码: {response.status_code}")
        logger.info(f"API 响应内容: {response.text[:500]}...")  # 只记录前500字符

        response.raise_for_status()  # 这会抛出HTTP错误

        # 5. 尝试解析JSON
        try:
            result = response.json()
            if "choices" not in result:
                raise ValueError("响应中缺少 'choices' 字段")

            return jsonify({
                "result": result["choices"][0]["message"]["content"]
            })

        except ValueError as e:
            logger.error(f"JSON 解析错误: {str(e)}")
            return jsonify({
                "error": f"API 返回了无效的JSON格式: {response.text[:200]}"
            }), 500

    except requests.exceptions.RequestException as e:
        logger.error(f"API 请求失败: {str(e)}")
        return jsonify({
            "error": f"DeepSeek API 请求失败: {str(e)}"
        }), 502

    except Exception as e:
        logger.error(f"未知错误: {str(e)}")
        return jsonify({
            "error": f"服务器内部错误: {str(e)}"
        }), 500